const http = require("http");
const fs = require("fs");
const url = require("url");
const path = require("path");
const mime = require("mime");

// console.log(mime.getType("1.js"));

const server = http.createServer((req, res) => {
  // console.log("请求进来了");
  // 路径处理
  let { pathname, query } = url.parse(req.url);
  pathname = decodeURIComponent(pathname); // 将中文path转出来
  // console.log(pathname);
  let absPath = path.join(__dirname, "html", pathname);
  console.log(absPath);

  // 2. 目标资源状态处置
  fs.stat(absPath, (err, statObj) => {
    console.log(err);
    if (err) {
      res.statusCode = 404;
      res.end("Not Found");
      return;
    }
    if (statObj.isFile()) {
      // 此时说明路径对应的目标是一个文件， 可以直接读取后会写
      fs.readFile(absPath, (err, data) => {
        // if (absPath.endsWith(".html")) {
        res.setHeader("Content-type", `${mime.getType(absPath)};charset=utf-8`);
        // }
        res.end(data);
      });
    } else {
      fs.readFile(path.join(absPath, "index.html"), (err, data) => {
        res.setHeader("Content-type", "text/html;charset=utf-8");
        res.end(data);
      });
    }
  });

  // res.end("111");
});

server.listen(1234, () => {
  console.log("服务启动成功");
});
